import 'dart:io';

import 'package:flutter/material.dart';
import 'package:wallet_utils/color.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:r_scan/r_scan.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

typedef RScanResultback = void Function(RScanResult result);

GlobalKey<_HtScanViewState> scanGlobalKey = GlobalKey();

class HtScanView extends StatefulWidget {
  double? offsetY;
  double? scanOffsetY;
  double? scanSize;
  RScanResultback? resultback;
  //扫码是否准备就绪回调
  ValueChanged<bool>? scanInitializeBlock;
  HtScanView(
      {this.offsetY,
      this.scanOffsetY,
      this.scanSize,
      this.resultback,
      this.scanInitializeBlock,
      Key? key})
      : super(key: key);
  @override
  _HtScanViewState createState() => _HtScanViewState();
}

class _HtScanViewState extends State<HtScanView>
    with SingleTickerProviderStateMixin {
  late RScanCameraController _controller;
  //是否使用扫描内容
  bool canScan = true;

  //扫描线
  late AnimationController _animatCcontroller;
  late Animation<AlignmentGeometry> _animation;

  @override
  void initState() {
    _animatCcontroller =
        AnimationController(duration: Duration(seconds: 2), vsync: this);
    _animation = Tween<AlignmentGeometry>(
            begin: Alignment.topCenter, end: Alignment.bottomCenter)
        .animate(_animatCcontroller);
    _animation.addStatusListener((status) {
      print(status);
      if (status == AnimationStatus.completed) {
        _animatCcontroller.repeat();
      }
    });
    //开始动画
    _animatCcontroller.forward();

    super.initState();
    initController();
  }

  bool loadFinish = false;

  Future<bool> canReadStorage() async {
    if (Platform.isIOS) return true;
    var status = await Permission.storage.status;
    if (status != PermissionStatus.granted) {
      var request = await Permission.storage.request();
      if (request != PermissionStatus.granted) {
        return false;
      }
    }
    return true;
  }

  Future<bool> canOpenCamera() async {
    var status = await Permission.camera.status;
    if (status != PermissionStatus.granted) {
      var request = await Permission.camera.request();
      if (request != PermissionStatus.granted) {
        return false;
      }
    }
    return true;
  }

  Future<void> initController() async {
    List<RScanCameraDescription> rScanCameras = await availableRScanCameras();
    _controller =
        RScanCameraController(rScanCameras[0], RScanCameraResolutionPreset.max);
    _controller.addListener(() {
      final result = _controller.result;
      if (result != null) {
        if (canScan) {
          print("widget.canScan --- ${canScan}");
          canScan = false;
          print('result---->${result.toString()}');
          if (widget.resultback != null) {
            widget.resultback!(result);
          }
        }
      }
    });

    if (widget.scanInitializeBlock != null) {
      widget.scanInitializeBlock!(false);
    }
    _controller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {
        loadFinish = true;
      });
      if (widget.scanInitializeBlock != null) {
        widget.scanInitializeBlock!(true);
      }
    });
    return;
  }

  @override
  void dispose() {
    print("相机释放了");
    _controller.dispose();
    _animatCcontroller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double offsetY = (widget.offsetY ?? 132.w).toInt().toDouble();
    double scanSize = (widget.scanSize ?? 200.w).toInt().toDouble();
    double offsetWidth = (ScreenUtil().screenWidth - scanSize) / 2.0;

    return loadFinish
        ? Container(
            width: ScreenUtil().screenWidth,
            height: ScreenUtil().screenHeight,
            child: Stack(
              children: [
                Positioned(
                  left: 0,
                  right: 0,
                  top: widget.scanOffsetY ?? 0,
                  bottom: 0,
                  child: AspectRatio(
                    aspectRatio: _controller.value.aspectRatio,
                    child: RScanCamera(
                      _controller,
                    ),
                  ),
                ),
                Positioned(
                  top: 0,
                  height: offsetY,
                  left: 0,
                  right: 0,
                  child: Container(
                    color: ColorManager.color000000.withOpacity(0.5),
                  ),
                ),
                Positioned(
                  top: offsetY,
                  width: offsetWidth,
                  left: 0,
                  bottom: 0,
                  child: Container(
                    color: ColorManager.color000000.withOpacity(0.5),
                  ),
                ),
                Positioned(
                  top: offsetY,
                  width: offsetWidth,
                  right: 0,
                  bottom: 0,
                  child: Container(
                    color: ColorManager.color000000.withOpacity(0.5),
                  ),
                ),
                Positioned(
                  bottom: 0,
                  top: offsetY + scanSize,
                  left: offsetWidth,
                  right: offsetWidth,
                  child: Container(
                    color: ColorManager.color000000.withOpacity(0.5),
                  ),
                ),
                Positioned(
                  height: 2.w,
                  width: 20.w,
                  top: offsetY,
                  left: offsetWidth,
                  child: Container(
                    color: ColorManager.color66BF1C,
                  ),
                ),
                Positioned(
                  height: 20.w,
                  width: 2.w,
                  top: offsetY,
                  left: offsetWidth,
                  child: Container(
                    color: ColorManager.color66BF1C,
                  ),
                ),
                Positioned(
                  height: 2.w,
                  width: 20.w,
                  top: offsetY,
                  right: offsetWidth,
                  child: Container(
                    color: ColorManager.color66BF1C,
                  ),
                ),
                Positioned(
                  height: 20.w,
                  width: 2.w,
                  top: offsetY,
                  right: offsetWidth,
                  child: Container(
                    color: ColorManager.color66BF1C,
                  ),
                ),
                Positioned(
                  height: 2.w,
                  width: 20.w,
                  top: offsetY + scanSize - 2.w,
                  left: offsetWidth,
                  child: Container(
                    color: ColorManager.color66BF1C,
                  ),
                ),
                Positioned(
                  height: 20.w,
                  width: 2.w,
                  top: offsetY + scanSize - 20.w,
                  left: offsetWidth,
                  child: Container(
                    color: ColorManager.color66BF1C,
                  ),
                ),
                Positioned(
                  height: 2.w,
                  width: 20.w,
                  top: offsetY + scanSize - 2.w,
                  right: offsetWidth,
                  child: Container(
                    color: ColorManager.color66BF1C,
                  ),
                ),
                Positioned(
                  height: 20.w,
                  width: 2.w,
                  top: offsetY + scanSize - 20.w,
                  right: offsetWidth,
                  child: Container(
                    color: ColorManager.color66BF1C,
                  ),
                ),
                Positioned(
                  height: scanSize,
                  width: scanSize,
                  top: offsetY,
                  right: offsetWidth,
                  child: Container(
                    child: AlignTransition(
                      alignment: _animation,
                      child: Image.asset(
                          "packages/hopson_utils/images/qr_code_line_icon.png",
                          width: scanSize),
                    ),
                  ),
                ),
              ],
            ))
        : Container(
            color: Colors.black,
          );
  }

  //暂停扫描
  void stopScaning() {
    _controller.stopScan();
  }

  //继续扫描
  void reScaning() {
    canScan = true;
    _controller.startScan();
  }

  //重置扫码模块
  void reloadScan() {
    canScan = true;
    initController();
  }
}
